package com.norra.client.ui

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Address
import android.location.Geocoder
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.core.app.ActivityCompat
import com.google.android.gms.maps.*
import com.google.android.gms.maps.model.LatLng
import com.norra.base.utils.PermissionUtils
import com.norra.base.utils.Toaster
import com.norra.client.R
import kotlinx.android.synthetic.main.activity_gps_select.*
import kotlin.concurrent.thread


class SelectGPSActivity : BaseActivity(), OnMapReadyCallback, View.OnClickListener {
    private var googleMap: GoogleMap? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_gps_select)
        setUpToolBar()
        supportActionBar?.title = getString(R.string.select_address)
        val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
        findViewById<View>(R.id.btn_confirm).setOnClickListener(this)
    }

    override fun onMapReady(googleMap: GoogleMap) {
        MapsInitializer.initialize(this)
        this.googleMap = googleMap
        if (PermissionUtils.hasPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
            googleMap.isMyLocationEnabled = true
        } else {
            if (PermissionUtils.canRequestPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 123)
            } else {
                Log.d("xxx", "Permission not enable");
            }
        }
        googleMap.moveCamera(CameraUpdateFactory.zoomTo(14f))
        googleMap.setOnCameraMoveListener {
            selected_lat.text = "Lat:  ${googleMap.cameraPosition.target.latitude}"
            selected_lng.text = "Lng: ${googleMap.cameraPosition.target.longitude}"
        }
        var setCenter = false
        if (intent.hasExtra("lat_lng")) {
            val latLng = intent.getParcelableExtra("lat_lng") as LatLng?
            if (latLng != null) {
                setCenter = true
                googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng))
                selected_lat.text = "Lat:  ${latLng.latitude}"
                selected_lng.text = "Lng: ${latLng.longitude}"
            }
        }
        if (!setCenter) {
            googleMap.moveCamera(CameraUpdateFactory.newLatLng(LatLng(59.32721, 18.07166)))
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 123 && permissions.contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                googleMap?.isMyLocationEnabled = true
            }
        }
    }

    override fun onClick(v: View?) {
        getAddressInfo()
    }

    private fun getAddressInfo() {
        val latLng = googleMap?.cameraPosition?.target

        if (latLng != null) {
            showLoadingView()
            thread(start = true) {
                val geocoder = Geocoder(this)
                val addressList = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1)

                if (addressList != null && addressList.isNotEmpty()) {
                    setGpsResult(latLng, addressList[0])
                } else {
                    setGpsResult(latLng, null)
                }
            }

        } else {
            Toaster.longToast("Get GPS Fail")
        }
    }


    private fun setGpsResult(latLng: LatLng, address: Address?) {
        runOnUiThread {
            hideLoadingView()
        }
        val resultIntent = Intent()
        resultIntent.putExtra("lat_lng", latLng)
        resultIntent.putExtra("address", address)
        setResult(RESULT_OK, resultIntent)
        finish()
    }

}